package com.atguigu.gmall.product.controller;

import lombok.SneakyThrows;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class CompletableFutureDemo {
    @SneakyThrows
    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2,
                5,
                3L,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(3));

        //创建futureA
        CompletableFuture<String> futureA = CompletableFuture.supplyAsync(() -> "hello");
        //创建futureB
        CompletableFuture<Void> futureB = futureA.thenAcceptAsync((t) -> {
            delaySec(1);
            printCurrTime(t + "futureB");
        }, threadPoolExecutor);
        //创建futureC
        CompletableFuture<Void> futureC = futureA.thenAcceptAsync((t) -> {
            delaySec(1);
            printCurrTime(t + "futureC");
        }, threadPoolExecutor);

        //创建线程池
//        // runAsync方法不支持返回值 supplyAsync支持返回值
//        CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(new Supplier<Integer>() {
//            @Override
//            public Integer get() {
//                System.out.println(Thread.currentThread().getName() + "正常");
////                int i = 1 / 0;
//                return 1024;
//            }
//        }).thenApply(new Function<Integer, Integer>() {
//            @Override
//            public Integer apply(Integer integer) {
//                //当一个线程依赖另一线程时，获取上一个任务的返回结果，并返回当前任务的返回值
//                System.out.println("thenapply" + integer);
//                return 1024 * 2;
//            }
//        }).whenComplete(new BiConsumer<Integer, Throwable>() {
//            @Override
//            public void accept(Integer integer, Throwable throwable) {
//                System.out.println("integer:" + integer);
//                System.out.println("throwable:" + throwable);
//
//            }
//        }).exceptionally(new Function<Throwable, Integer>() {
//            @Override
//            public Integer apply(Throwable throwable) {
//                System.out.println("throwable:" + throwable);
//                return 404;
//            }
//        });
//        System.out.println(integerCompletableFuture.get());
//    }
    }

    //打印方法
    private static void printCurrTime(String s) {
        System.out.println(s);
    }

    //睡眠方法
    private static void delaySec(int i) {
        try {
            Thread.sleep(i * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
